package com.mall.common.security;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.RegexUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;

import com.mall.common.service.OperateService;

public class ResourceFilterInvocationDefinitionSource implements InitializingBean, FilterInvocationSecurityMetadataSource {
	@Resource private OperateService operateService;

	private UrlMatcher urlMatcher;
	private boolean useAntPath = true;
	private boolean setpathlowercase = true;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		if(this.useAntPath){
			urlMatcher = new AntUrlPathMatcher();
			if(setpathlowercase){
				((AntUrlPathMatcher)urlMatcher).setRequiresLowerCaseUrl(true);
			}
		}else{
			urlMatcher = new RegexUrlPathMatcher();
			if(setpathlowercase){
				((RegexUrlPathMatcher)urlMatcher).setRequiresLowerCaseUrl(true);
			}
		}
	}
	
	@Override
	public Collection<ConfigAttribute> getAttributes(Object filter) throws IllegalArgumentException {
		FilterInvocation filterInvocation = (FilterInvocation)filter;
		
		Map<String, String> urlRoles = operateService.getAllUrlRole();
		//取得了资源表的数据
		if(urlRoles == null || urlRoles.size() == 0){
			return null;
		}
		//当前的url请求路径
		String requestURL = filterInvocation.getRequestUrl();
		//把用户请求的路径进行授权Role，因为我们是从资源表的数据已经保存在application中
		String grantRoleStr = null;
		for (Iterator<Map.Entry<String, String>> iterator = urlRoles.entrySet().iterator(); iterator.hasNext();) {
			Map.Entry<String, String> entry = iterator.next();
			String url = entry.getKey();//路径名
			String[] patterns = url.split(",");
			for(String pattern : patterns){
				if(urlMatcher.pathMatchesUrl(pattern, requestURL)){
					grantRoleStr = entry.getValue();
					break;
				}
			}
			if(StringUtils.isNotBlank(grantRoleStr)){
				break;
			}
		}
		
		if(grantRoleStr != null){
			return SecurityConfig.createListFromCommaDelimitedString(grantRoleStr);
		}
		//当前用户的请求的路径
		return null;
	}
	
	@Override
	public boolean supports(Class<?> arg0) {
		return true;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

}
